/**
 * Created with JetBrains PhpStorm.
 * User: wdj
 * Date: 14-5-13
 * Time: 11:25
 * To change this template use File | Settings | File Templates.
 */

var Timer = function(opt){
    for(var key in opt){
        this.defaults[key] = opt[key];
    }
    this.defaults.startDate = new Date(new Date().getTime() + opt.totalTimes * 1000);
}

Timer.prototype = {
    defaults:{
        totalTimes : 0,
        currentTimes : 0,
        C : null,
        S : null,
        startDate : null
    },
    __timer:null,
    run: function(){
        var self = this;
        self.defaults.currentTimes++;
        if(self.defaults.currentTimes < self.defaults.totalTimes){
            var s = self.defaults.totalTimes - self.defaults.currentTimes;
            if(typeof self.defaults.S == 'function')self.defaults.S.call(self,s);
            self.__timer = setTimeout(function(){
                self.run.call(self);
            },1000);
        }else if(typeof self.defaults.C == 'function'){
            self.defaults.C.call(self);
        }
        return self;
    },
    start: function(){
      return this.run();
    },
    delay: function(s){
        this.defaults.totalTimes += parseInt(s);
        return this;
    },
    format: function(s){
        var iHour = parseInt((s / 3600) % 24);
        iHour < 10 ? iHour = "0" + iHour : iHour;
        var iMinute = parseInt((s / 60) % 60);
        iMinute < 10 ? iMinute = "0" + iMinute : iMinute;
        var iSecond = s % 60;
        iSecond < 10 ? iSecond = '0' + iSecond : iSecond;
        return {
            h: iHour,
            m: iMinute,
            s: iSecond
        };
    },
    stop: function(){
        if(this.__timer)clearTimeout(this.__timer);
        return this;
    },
    reset: function(){
        this.defaults.currentTimes = 0;
        return this;
    }
};